package com.itheima.prince.smartpeking.impl.NewsCenterPagers.NewsCenterDetailBase;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.itheima.prince.smartpeking.R;
import com.itheima.prince.smartpeking.activity.NewsDetailUI;
import com.itheima.prince.smartpeking.base.BaseMenuPager;
import com.itheima.prince.smartpeking.base.TabdetailVIewPager;
import com.itheima.prince.smartpeking.bean.NewsCenterBean;
import com.itheima.prince.smartpeking.bean.TableDetailBean;
import com.itheima.prince.smartpeking.utils.ConstantUtil;
import com.itheima.prince.smartpeking.utils.SPUtil;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/10/26 0026.
 */
public class NewCenDeBase extends BaseMenuPager {
    private static final String LV_TEXT_CACHE = "lv_text_cahce";
    private NewsCenterBean.DataBean.ChildrenBean mchildrenBean;
    private TabdetailVIewPager mvp_newsdetail;
    private PullToRefreshListView mlv_pagerdetail_listnews;
    private TextView mtv_tabdetail_imgetext;
    private List<TableDetailBean.DataBean.TopnewsBean> topnews;
    private LinearLayout mll_tabletail_dot;
    private int currentIndexDot = 0;
    private List<TableDetailBean.DataBean.NewsBean> news;
    private MybaseAdapter mybaseAdapter;
    private TableDetailBean tableDetailBean;
    public int status;
    private List<TableDetailBean.DataBean.NewsBean> morenews;
    private MyHandler myHandler;


    public NewCenDeBase(Context context, NewsCenterBean.DataBean.ChildrenBean childrenBean) {
        super(context);
        this.mchildrenBean = childrenBean;
    }


    @Override
    protected View initview() {
        View view = View.inflate(mcontext, R.layout.pager_detail, null);
        View headView = View.inflate(mcontext, R.layout.include_headview_newsdetail, null);
        mvp_newsdetail = (TabdetailVIewPager) headView.findViewById(R.id.vp_pagerdetail_topimage);
        mlv_pagerdetail_listnews = (PullToRefreshListView) view.findViewById(R.id.lv_pagerdetail_listnews);
        mtv_tabdetail_imgetext = (TextView) headView.findViewById(R.id.tv_tabdetail_imgetext);
        mll_tabletail_dot = (LinearLayout) headView.findViewById(R.id.ll_tabletail_dot);
        // mlv_pagerdetail_listnews.addHeaderView(headView);
        //设置头布局的另外方法
        AbsListView.LayoutParams mlayoutParams =
                new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        headView.setLayoutParams(mlayoutParams);
        ListView mlistView = mlv_pagerdetail_listnews.getRefreshableView();
        mlistView.addHeaderView(headView);

        //设置上下模式
        mlv_pagerdetail_listnews.setMode(PullToRefreshBase.Mode.BOTH);

        //初始化各个状态的刷新布局
        init();
        mlv_pagerdetail_listnews.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (tableDetailBean == null) {
                    Toast.makeText(mcontext, "你进入了没有网络的异次元", Toast.LENGTH_SHORT).show();
                    return;
                }
                new FinishDownRefresh().execute();
                mybaseAdapter.notifyDataSetChanged();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (tableDetailBean == null) {
                    Toast.makeText(mcontext, "你进入了没有网络的异次元", Toast.LENGTH_SHORT).show();
                    return;
                }
                new FinishUpRefresh().execute();
                mybaseAdapter.notifyDataSetChanged();
            }
        });


        return view;
    }

    private class FinishDownRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                requestDownInternet();
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
//          adapter.notifyDataSetChanged();
//            mlv_pagerdetail_listnews.onRefreshComplete();
//            if (status==0){
//                Toast.makeText(mcontext, "网络有问题哦", Toast.LENGTH_SHORT).show();
//            }

        }
    }

    private void requestDownInternet() {
        OkHttpUtils
                .get()
                .url(ConstantUtil.SERVER_URL + mchildrenBean.getUrl())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mlv_pagerdetail_listnews.onRefreshComplete();
                        Toast.makeText(mcontext, "网络有问题哦", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.d("aaa", "下拉刷新成功" + response);
                        mlv_pagerdetail_listnews.onRefreshComplete();
                        Toast.makeText(mcontext, "加载成功", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private class FinishUpRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (TextUtils.isEmpty(tableDetailBean.getData().getMore())) {
                    status = 0;
                } else {
                    requestUpInternet();
                    status = 1;
                }

                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
//          adapter.notifyDataSetChanged();
            mlv_pagerdetail_listnews.onRefreshComplete();
            if (status == 0) {
                Toast.makeText(mcontext, "没有更多的数据了", Toast.LENGTH_SHORT).show();
            } else {
                if (morenews == null) {
                    Toast.makeText(mcontext, "网络异常", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mcontext, "成功地刷新了" + morenews.size() + "条新闻", Toast.LENGTH_SHORT).show();

                }
            }
        }
    }

    private void requestUpInternet() {
        OkHttpUtils
                .get()
                .url(ConstantUtil.SERVER_URL + tableDetailBean.getData().getMore())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.d("aaa", "onError: 访问失败");
                        mlv_pagerdetail_listnews.onRefreshComplete();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.d("刷新更新成功", "onResponse: ");
                        parseMoreJson(response);

                    }


                });
    }

    private void parseMoreJson(String response) {
        Gson gson = new Gson();
        tableDetailBean = gson.fromJson(response, TableDetailBean.class);
        morenews = tableDetailBean.getData().getNews();
        news.addAll(morenews);
    }


    private void init() {
        ILoadingLayout startLabels = mlv_pagerdetail_listnews
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

        ILoadingLayout endLabels = mlv_pagerdetail_listnews.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
    }

    @Override
    public void initData() {
        String cacheJson = SPUtil.getString(mcontext, mchildrenBean.getUrl(), "");
        if (!TextUtils.isEmpty(cacheJson)) {
            parseJason(cacheJson);
        }
        OkHttpUtils
                .get()
                .url(ConstantUtil.SERVER_URL + mchildrenBean.getUrl())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.d("aaa", e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.d("aaa", mchildrenBean.getTitle() + "访问成功\n" + response);
                        parseJason(response);
                        SPUtil.putString(mcontext, mchildrenBean.getUrl(), response);
                    }


                });

    }

    private void parseJason(String response) {
        Gson gson = new Gson();
        tableDetailBean = gson.fromJson(response, TableDetailBean.class);
        //String title = tableDetailBean.getData().getNews().get(1).getTitle();
        //Log.d("bbb", "解析出来的数据是：   "+title);
        //展示顶部的轮播图
        topnews = tableDetailBean.getData().getTopnews();
        news = tableDetailBean.getData().getNews();
        final TopNewsAdapter madapter = new TopNewsAdapter();
        mvp_newsdetail.setAdapter(madapter);
        //初始化第一个页面的文字
        mtv_tabdetail_imgetext.setText(topnews.get(0).getTitle());
        //初始化右下角红点   params是设置的子空间的一些属性，和父控件没关系

        mll_tabletail_dot.removeAllViews();
        for (int i = 0; i < topnews.size(); i++) {
            ImageView imageView = new ImageView(mcontext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
            layoutParams.leftMargin = 20;
            imageView.setLayoutParams(layoutParams);
            imageView.setEnabled(false);
            imageView.setBackgroundResource(R.drawable.selecotr_newsdetail_reddot);
            mll_tabletail_dot.addView(imageView);
        }
        //初始化第一个红点的位置
        mll_tabletail_dot.getChildAt(0).setEnabled(true);


        mvp_newsdetail.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //设置图片左下角的文字
                mtv_tabdetail_imgetext.setText(topnews.get(position).getTitle());

                //设置图片右下角的点的选中状态
                mll_tabletail_dot.getChildAt(currentIndexDot).setEnabled(false);
                mll_tabletail_dot.getChildAt(position).setEnabled(true);

                currentIndexDot = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        currentIndexDot = 0;

        //给listview设置adpater
        mybaseAdapter = new MybaseAdapter();
        mlv_pagerdetail_listnews.setAdapter(mybaseAdapter);

        //设置轮播图的自动滚动使用handler
        if (myHandler == null) {
            myHandler = new MyHandler();
        }
        //清除前面发送的消息
        myHandler.removeCallbacksAndMessages(null );
        myHandler.sendMessageDelayed(Message.obtain(), 3000);


        //设置listview点击之后的字体缓存
        mlv_pagerdetail_listnews.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("aaa", position + "");
                int realposition = position - 2;
                int id1 = news.get(realposition).getId();
                String ids = String.valueOf(id1);
                String cacheString = SPUtil.getString(mcontext, LV_TEXT_CACHE, "");
                String temp;
                if (!cacheString.contains(ids)) {
                    temp = cacheString + "," + ids;
                    SPUtil.putString(mcontext, LV_TEXT_CACHE, temp);
                }
                mybaseAdapter.notifyDataSetChanged();

                Intent intent = new Intent(mcontext, NewsDetailUI.class);
                intent.putExtra("url", news.get(realposition).getUrl());
                mcontext.startActivity(intent);

                Log.d("bbb", news.get(realposition).getUrl());


            }
        });


    }

    class MyHandler extends android.os.Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.d("bbb", "handleMessage: "+myHandler );

            //如果顶部viewpager不在显示的时候，取消发送
            if (mvp_newsdetail.getWindowVisibility()==View.GONE){
                myHandler.removeCallbacksAndMessages(null);
                return;
            }



            //设置模数，来重回第一
            int nexPage =(mvp_newsdetail.getCurrentItem()+1)%mvp_newsdetail.getAdapter().getCount();
            mvp_newsdetail.setCurrentItem(nexPage);
            myHandler.sendMessageDelayed(Message.obtain(),3000);
            super.handleMessage(msg);
        }
    }


    class MybaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (news == null) {
                return 0;
            } else {
                return news.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        //converView是为了减少inflate的使用
        //converVIew是为了减少findviewbyid
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = View.inflate(mcontext, R.layout.item_tabdetail_news, null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_item_newdtail);
                viewHolder.textView = (TextView) convertView.findViewById(R.id.tv_text_newdetail);
                viewHolder.time = (TextView) convertView.findViewById(R.id.tv_time_newsdetail);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //判断缓存的颜色
            String cache = SPUtil.getString(mcontext, LV_TEXT_CACHE, "");
            int id = news.get(position).getId();
            String nowid = String.valueOf(id);
            //在复用里面必须有else，否则会复用
            if (cache.contains(nowid)) {
                viewHolder.textView.setTextColor(Color.GRAY);
            } else {
                viewHolder.textView.setTextColor(Color.BLACK);
            }

            Picasso.with(mcontext).load(news.get(position).getListimage()).into(viewHolder.imageView);
            viewHolder.textView.setText(news.get(position).getTitle());
            viewHolder.time.setText(news.get(position).getPubdate());
            return convertView;
        }
    }


    class ViewHolder {
        public ImageView imageView;
        public TextView textView;
        public TextView time;
    }


    class TopNewsAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (topnews == null) {
                return 0;
            }
            return topnews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(mcontext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            container.addView(imageView);

            //监听图片的触摸方法，按下暂停轮播，放开或者取消触摸时候重新开始轮播
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            myHandler.removeCallbacksAndMessages(null);//此方法取消handler
                            break;
                        case MotionEvent.ACTION_UP:
                            myHandler.sendMessageDelayed(Message.obtain(),3000);
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            myHandler.sendMessageDelayed(Message.obtain(),3000);
                            break;
                    }

                    return true; //确定本控件会消费时间
                }
            });



            Picasso.with(mcontext).load(topnews.get(position).getTopimage()).into(imageView);
            Log.d("bbb", topnews.get(position).getTopimage());
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
